﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ECare.BUS.Data;
using ECare.Database;

namespace ECare.BUS.Workers
{
  public   class CreateResourcesWorker:BackgroundWorker
    {

      public List<PlanInfo> Plans { get; set; }

      public CreateResourcesWorker()
      {
          this.DoWork += CreateResourcesWorker_DoWork;
      }

      void CreateResourcesWorker_DoWork(object sender, DoWorkEventArgs e)
      {
          if (this.Plans == null)
          {
              e.Result = false;
              return;
          }
          if (this.Plans.Count == 0)
          {
              e.Result = false;
              return;
          }
          var table = new DataTable();
          //资源号
          var resourceColumn = new DataColumn("resourceId", typeof(System.Int32));
          table.Columns.Add(resourceColumn);

          //资源名称
          var resourceNamecolumn = new DataColumn("resourceName", typeof(System.String));
          table.Columns.Add(resourceNamecolumn);

          //需要数量
          var resourceDecimalcolumn = new DataColumn("NeededNumber", typeof(System.Decimal));
          table.Columns.Add(resourceDecimalcolumn);

          //四舍五入
          var resourceIntcolumn = new DataColumn("NeededInt", typeof(System.Int32));
          table.Columns.Add(resourceIntcolumn);
          
          //生产库存
          var resourceProduceDecimalcolumn = new DataColumn("ProduceNumber", typeof(System.Decimal));
          table.Columns.Add(resourceProduceDecimalcolumn);

          //实际库存
          var resourceStorageDecimalcolumn = new DataColumn("StorageNumber", typeof(System.Decimal));
          table.Columns.Add(resourceStorageDecimalcolumn);

          using (var context = new Entities())
          {

              string planIds = string.Empty;
              foreach (var plan in this.Plans)
              {
                  if (string.IsNullOrEmpty(planIds))
                  {
                      planIds = plan.plan_id.ToString();
                  }
                  else
                  {
                      planIds = planIds + "," + plan.plan_id;
                  }
              }

              var res = context.sp_getresources(planIds);


              foreach (var result in res)
              {
                  var newRow = table.NewRow();
                  newRow["resourceId"] = result.resource_Id.ToString();
                  newRow["NeededNumber"] = result.number;
                  newRow["ProduceNumber"] = result.leftInProducing;
                  newRow["StorageNumber"] = result.LeftInStorage;

                  table.Rows.Add(newRow);
              }

          }
          e.Result = table;

      }

    }
}
